package cn.kbyue.swagger3.config;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

/**
 * zuul filter
 * @link https://www.cnblogs.com/dalaoyang/p/12005283.html
 *
 * 当模块中加入了 context-path 时，需要使用拦截器进行处理
 * 注：这里默认 service-id 和 context-path 一致，如果不一致，需要在 run() 中做特殊处理
 *
 * @author xl
 * @date 2020/9/1 22:29
 */
@Component
public class UrlPathFilter extends ZuulFilter{

    Logger logger = LoggerFactory.getLogger(UrlPathFilter.class);

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 6;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        Object requestURI = requestContext.get(FilterConstants.REQUEST_URI_KEY);
        Object server = requestContext.get(FilterConstants.PROXY_KEY);
        String finalURI = "/" + server + requestURI;

        logger.info(">>> Filter Url:: requestURI: {}, server: {}, finalURI: {}", requestURI, server, finalURI);
        // eg: >>> Filter Url:: requestURI: /msg, server: eureka-client, finalURI: /eureka-client/msg

        requestContext.put(FilterConstants.REQUEST_URI_KEY, finalURI);
        return null;
    }
}
